package web.blogsphere.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import web.blogsphere.constant.Constants;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JWTUtils
 * @Description JWT 登录
 * @Author ZJX
 * @Date 2024/9/4 13:01
 * @Version 1.0
 */

@Slf4j
public class JwtUtils {

    private static final long JWT_EXPIRATION = 60 * 60 * 1000 ; // 过期时间
    private static final String secretStr = "Le++o8NQWVXWo3+SJtAtnjBW9iA0OvPL0c0mMrol2fU="; // 密钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr)); // Base64 编码的字符串

//    生成 token gen是 generate 缩写
    public static String genJwtToken(Map<String, Object> claim){

        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION))
                .signWith(key)
                .compact();
        System.out.println();
        return token;
    }

//    校验 token    Claims 为 null 表示校验失败
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析token失败, token:{}", token);
            return null;
        }
        return claims;
    }

//    根据给定的JWT令牌获取用户ID
    public static Integer getIdByToken(String token){
//        // 解析JWT令牌，获取Claims对象
        Claims claims = parseToken(token);

        if (claims != null){
            Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
            if (userId > 0){
                return userId;
            }
        }
        return null;
    }

}
